package com.gmss.crawler.constants;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gmss.crawler.enums.CommonEnum;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Base implements ServletContextAware {
    /**
     * 日志
     **/
    protected final Logger log = LoggerFactory.getLogger(Base.class);


    public HttpServletRequest request;
    public HttpServletResponse response;
    public HttpSession session;
    public ServletContext application;
    /**
     * 文件
     **/
    @Autowired(required = false)
    protected MultipartResolver multipartResolver;

    /**
     * @param code
     * @return
     */
    public static String respJson(CommonEnum code) {
        return respJson(code, null);
    }

    /**
     * @param code
     * @param data
     * @return
     */
    public static String respJson(CommonEnum code, Object data) {
        JSONObject jsono = new JSONObject();
        jsono.put("code", code.getCode());
        jsono.put("message", code.getMessage());
        if (data != null) {
            jsono.put("data", data);
        }
        return jsono.toJSONString();
    }

    public static String respJson(CommonEnum code, Object data, Object total) {
        JSONObject jsono = new JSONObject();
        jsono.put("code", code.getCode());
        jsono.put("message", code.getMessage());
        if (data != null) {
            jsono.put("data", data);
        }
        if (null != total)
            jsono.put("total", total);
        return jsono.toJSONString();
    }

    /**
     * @param code    错误码
     * @param message 内容
     * @return
     */
    public static String respJson(String code, String message) {
        return respJson(code, message, null);
    }

    /**
     * @param code
     * @param message
     * @param data
     * @return
     */
    public static String respJson(String code, String message, Object data) {
        JSONObject jsono = new JSONObject();
        jsono.put("code", code);
        jsono.put("message", message);
        if (data != null) {
            jsono.put("data", data);
        }
        return JSON.toJSONString(jsono);
    }

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     * 获取传递过来的参数
     */
    public String getParameter(String key) {
        return request.getParameter(key);
    }

//    /**
//     * 分页对象
//     */
//    public Pageable getPage() {
//        String pageNo = getParameter("pageNum");
//        if (StringUtils.isEmpty(pageNo))
//            pageNo = getParameter("page");
//        String pageSize = getParameter("pageSize");
//        if (StringUtils.isEmpty(pageSize))
//            pageSize = getParameter("limit");
//        if (StringUtils.isEmpty(pageSize))
//            pageSize = getParameter("rows");
//        int pageNum = StringUtils.isEmpty(pageNo) ? 0 : Integer.parseInt(pageNo) - 1;
//        int rows = StringUtils.isEmpty(pageSize) ? 10 : Integer.parseInt(pageSize);
//        Pageable pageable = new PageRequest(pageNum, rows);
//        return pageable;
//    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.application = servletContext;
    }

    /**
     * binder用于bean属性的设置
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }
}


/**
 * 处理日期格式转换问题
 */
class DateEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isEmpty(text)) {
            return;
        }
        text = text.trim();
        Pattern pattern = Pattern.compile("[^0-9]");
        Matcher matcher = pattern.matcher(text);
        text = matcher.replaceAll("");

        int length = text.length();
        Date date;
        switch (length) {
            case 19:
                if (text.indexOf("/") > 0)
                    date = DateTime.parse(text, DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss")).toDate();
                if (text.indexOf("-") > 0)
                    date = DateTime.parse(text, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
            case 14:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHHmmss")).toDate();
                break;
            case 12:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHHmm")).toDate();
                break;
            case 10:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMddHH")).toDate();
                break;
            case 8:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMMdd")).toDate();
                break;
            case 6:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyyMM")).toDate();
                break;
            case 4:
                date = DateTime.parse(text, DateTimeFormat.forPattern("yyyy")).toDate();
                break;
            default:
                return;
        }
        setValue(date);
    }
}

/**
 * 处理string类型两头空白
 */

class StringEscapeEditor extends PropertyEditorSupport {

    public StringEscapeEditor() {
        super();
    }

    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }

    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            value = value.trim();
            setValue(value);
        }
    }
}
